package com.suzao.rabbitmq.producer;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.suzao.rabbitmq.entity.Merchant;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Component;

/**
 * @classname: RabbitSender
 * @description:
 * @author: mc
 * @create: 2020-10-29 15:29
 **/
@Component
@PropertySource("classpath:rabbitmq.properties")
public class RabbitSender {

    @Value("${com.suzao.directexchange}")
    private String directExchange;
    @Value("${com.suzao.topicexchange}")
    private String topicExchange;
    @Value("${com.suzao.fanoutexchange}")
    private String fanoutExchange;
    @Value("${com.suzao.directroutingkey}")
    private String directRoutingKey;
    @Value("${com.suzao.topicroutingkey1}")
    private String topicroutingkey1;
    @Value("${com.suzao.topicroutingkey2}")
    private String topicroutingkey2;

    //自定义的模板，所有消息都会转换成JSON发送
    @Autowired
    AmqpTemplate suzaoTemplate;

    public void send() throws JsonProcessingException {
        Merchant merchant = new Merchant(1001,"a dirext msg: 北京大学","中国北京市海淀区1号");
        suzaoTemplate.convertAndSend(directExchange , directRoutingKey,merchant);

        suzaoTemplate.convertAndSend(topicExchange,topicroutingkey1 , "a topic msg: shanghai.suzao.teacher");
        suzaoTemplate.convertAndSend(topicExchange,topicroutingkey2 , "a topic msg: changsha.suzao.teacher");

        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(merchant);
        System.out.println("send : "+ json);
        suzaoTemplate.convertAndSend(fanoutExchange,"",json);

    }
}
